//
//  commentViewController.m
//  UESTCPioneer
//
//  Created by Sway on 14-3-22.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "commentViewController.h"
#import"commentView.h"
#import "commentTableViewCell.h"
#define backgroundColor [UIColor colorWithRed:237.0/255.0 green:237.0/255.0 blue:237.0/255.0 alpha:1]

#pragma mark - commentTableView

@interface commentTableView : UPTableView

@end

@implementation commentTableView

@end

@interface commentViewController ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,commentBackDelegate>
{
    //    commentTableView *TableView;
    NSArray *tableViewDataArray;
    NSMutableArray *tableContentBodyFrameArray;
    UIImageView * tvImageView;
    NSString * text;
    NSString * commentBackName;
}

@property (nonatomic,strong) UITextView * questTV;
@property (nonatomic,strong) UIToolbar  * toolBar;
@property (nonatomic,strong) UIButton   * completeBtn;
@property (nonatomic,strong) UIButton   * cancelBtn;
@property (nonatomic,strong) UILabel    * tvLabel;
@end
#pragma mark - commentViewController

static NSString *cellIdentifier=@"cell";

@implementation commentViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self.navigationController.navigationBar setTranslucent:YES];
    [self.view setBackgroundColor:backgroundColor];
//    [self.tableView removeFromSuperview];
//    self.tableView=[[UITableView alloc]init];
    
    
    
//    [self.view addSubview:self.tableView];
    [self.tableView setBackgroundColor:backgroundColor];
//    [self.view setBackgroundColor:[UIColor blueColor]];
//    [self.tableView setTranslatesAutoresizingMaskIntoConstraints:YES];
//    [self.tableView setFrame:CGRectMake(0, 0, 320, 455)];
    

    tableViewTopConstraint.constant=0;
//    TableView=[[commentTableView alloc]initWithFrame:self.view.bounds];
    [self.tableView registerClass:[commentTableViewCell class] forCellReuseIdentifier:cellIdentifier];
//    [self.view addSubview:TableView];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;

    
//    NSLog(@"%f,%f,%f,%f",self.tableView.frame.origin.x,self.tableView.frame.origin.y,self.tableView.frame.size.width,self.tableView.frame.size.height);
    
    
//    [self.tableView setTranslatesAutoresizingMaskIntoConstraints:YES];
//    CGRect re = self.tableView.frame;
//    re.origin.y=0;
//    [self.tableView setFrame:re];
//    NSLog(@"%f",self.tableView.frame.origin.y);

//    [self.tableView setFrame:<#(CGRect)#>]

    
    
//    [self.tableView setClipsToBounds:NO];
//    [self.tableView setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [self.tableView removeConstraints:self.tableView.constraints];
//    __weak UITableView *table = self.tableView;
////    [self.tableView setBackgroundColor:[UIColor redColor]];
//    [table setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[table]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(table)]];
//        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[table]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(table)]];
    
    
//    tableViewTopConstraint.constant=0;
//    NSLog(@"%@",self.view.subviews);
//    NSLog(@"%@",self.view.constraints);
//    [self.tableView reloadData];
//    [self.view setNeedsLayout];
//    [self.tableView setContentInset:UIEdgeInsetsMake(-30, 0, 0, 0)];

//    [self.tableView beginRefreshing];
    
	// Do any additional setup after loading the view.
    [self.completeBtn addTarget:self action:@selector(completeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.toolBar addSubview:self.questTV];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.toolBar];
    
    
    text = [NSString string];
    commentBackName = [NSString string];
    tableContentBodyFrameArray = [NSMutableArray array];
    
    [self registerForKayboardNotifications];
}



//@设置评论数的方法
-(void)setNumberOfComment:(NSInteger)numberOfComment{
    _numberOfComment=numberOfComment;
    [self.navigationItem setRightBarButtonItem:Nil];
#pragma mark 加导航栏按钮
    //    UIView *customView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 88, 44)];
    UIButton *commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [customView addSubview:commentButton];
    
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 18, 18)];
    [imageView setImage:[UIImage imageNamed:@"com.png"]];
    [commentButton addSubview:imageView];
    
    //    [commentButton setFrame:customView.bounds];
    [commentButton setTitle:[NSString stringWithFormat:@"%d",self.numberOfComment] forState:UIControlStateNormal];
    [commentButton addTarget:self action:@selector(commentButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [commentButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 24, 24)];
    UIBarButtonItem *rightCommentBarButton=[helper BarButtonItemWithUIButton:commentButton ButtonOrigin:CGPointMake(46, 13) CustomViewSize:CGSizeMake(88, 44)];
    //    NSLog(@"%@",self.navigationController.navigationItem.leftBarButtonItems);
    
    [self.navigationItem setRightBarButtonItem:rightCommentBarButton];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableview Delegate and DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * content = tableViewDataArray[indexPath.row][@"commentBody"];
    CGSize contentSize = [content sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.view.frame.size.width - 20, MAXFLOAT)];
    CGFloat height = contentSize.height;
    tableContentBodyFrameArray[indexPath.row] = [NSString stringWithFormat:@"%f",height];
    return height + 28.0f + 35.0f;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  [tableViewDataArray count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    commentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    [cell.headImageView setImageWithURL:tableViewDataArray[indexPath.row][@"headImageUrl"] placeholderImage:[UIImage imageNamed:@"defaultHeadImage.png"]];
    cell.commentDelegate = self;
    cell.userName.text=tableViewDataArray[indexPath.row][@"userName"];
    cell.commentBody.text=tableViewDataArray[indexPath.row][@"commentBody"];
    cell.commentTime.text = tableViewDataArray[indexPath.row][@"commentDate"];
    
    NSString * myName = [constant getUserName];
    if (![_commentFlag isEqualToString:@"PartyActivity"]) {
        cell.commentBack.hidden = YES;
    }else{
        if ([cell.userName.text isEqualToString:myName]) {
            cell.commentBack.hidden = YES;
        }else{
            cell.commentBack.hidden = NO;
        }
    }
    
    [cell setCommentBodyFrame:[tableContentBodyFrameArray[indexPath.row] floatValue]];
//    cell.userInteractionEnabled = NO;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


#pragma mark - commentButton press
-(void)commentButtonPress:(UIButton*)button{
    
    return;
   __weak commentViewController *weakSelf=self;
    
    commentView *co=[[commentView alloc]init];
    
    [co popUpCommentViewWithCommitBlock:^(NSString *commentBody) {
        NSMutableDictionary *dic= [[NSMutableDictionary alloc]initWithDictionary:weakSelf.commentRequestData];
//        [weakSelf.commentRequestData setObject:@"comment" forKey:commentBody];
        dic[_commentContentKey]=commentBody;
        self.commentRequestData=[[NSDictionary alloc]initWithDictionary:dic];
        [NetworkCenter AFRequestWithData:self.commentRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
            if ([dic[@"result"] isEqualToString:@"success"]){
                [Alert showAlert:@"评论成功"];
                self.numberOfComment++;
                [self.tableView beginRefreshing];
            }
            else {
                [Alert showAlert:@"评论失败"];
            }
            
            //弹出提示：评论成功
//            NSLog(@"评论成功");
            [co closeCommentView];
            
        } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            //弹出提示：评论失败
            NSLog(@"评论失败");
        }];
    }];
}

-(void)pullUpRefresh:(MJRefreshBaseView *)refreshView{
    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc]initWithDictionary:self.commentListRequestData];
    [tempDic setObject:[NSString stringWithFormat:@"%d",PullUpRefreshTimes+2] forKey:@"page"];
    
//    self.commentListRequestData = [[NSDictionary alloc]initWithDictionary:tempDic];
    
    
    [NetworkCenter AFRequestWithData:tempDic SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {

        NSError *error;

        NSArray *arr=[NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:&error];
        
        //如果空
        if ([arr count]==0){
            [refreshView endRefreshing];
            return ;
        }
        
        NSMutableArray *targetArray = [[NSMutableArray alloc]init];
        for (NSDictionary *sourceDic in arr){
            
            NSMutableDictionary *targetDic = [[NSMutableDictionary alloc]init];
            
            
            
            [targetDic setObject:@"" forKey:@"headImageUrl"];
            
            //@根据映射字典把服务器返回json的字段映射到本地字段如commentAuthor->userName,commentContent->commentBody
            NSEnumerator *keyEnumerator=[_commentListKeyMapping keyEnumerator];
            NSString *key;
            while((key=[keyEnumerator nextObject])!=nil){
                    [targetDic setObject:sourceDic[key]  forKey:_commentListKeyMapping[key]];
            }

//            [targetDic setObject:sourceDic[@"userName"]  forKey:@"userName"];
//            [targetDic setObject:sourceDic[@"comment"] forKey:@"commentBody"];
            [targetArray addObject:targetDic];
        }
        
        NSMutableArray *muArr = [[NSMutableArray alloc]initWithArray:tableViewDataArray];
        [muArr addObjectsFromArray:targetArray];
        tableViewDataArray = [[NSArray alloc]initWithArray:muArr];
//        tableViewDataArray=targetArray;
        [refreshView endRefreshing];
        [self.tableView reloadData];
        
        PullUpRefreshTimes++;
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"commentViewController init request error:%@",error);
    }];
}
-(void)pullDownRefresh:(MJRefreshBaseView *)refreshView{
    [NetworkCenter AFRequestWithData:self.commentListRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        
        NSError *error;
        NSArray *arr=[NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:&error];
        
        NSMutableArray *targetArray = [[NSMutableArray alloc]init];
        for (NSDictionary *sourceDic in arr){
            
            NSMutableDictionary *targetDic = [[NSMutableDictionary alloc]init];
            [targetDic setObject:@"" forKey:@"headImageUrl"];
            
            //@根据映射字典把服务器返回json的字段映射到本地字段如commentAuthor->userName,commentContent->commentBody
            NSEnumerator *keyEnumerator=[_commentListKeyMapping keyEnumerator];
            NSString *key;
            while((key=[keyEnumerator nextObject])!=nil){
                [targetDic setObject:sourceDic[key]  forKey:_commentListKeyMapping[key]];
            }
            [targetArray addObject:targetDic];
        }
        tableViewDataArray=targetArray;
        [refreshView endRefreshing];
        [self.tableView reloadData];
        PullUpRefreshTimes=0;
        
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"commentViewController init request error:%@",error);
    }];
}

/****************************************************************************************/
-(void)_loadUPTableView{
    self.tableView=[[UPTableView alloc]initWithFrame:CGRectMake(0, 0, 320,self.view.frame.size.height - 35 - 64) style:UITableViewStyleGrouped];
    self.tableView.tag = 27;
    [self.view addSubview:self.tableView];
}


-(UITextView *)questTV{
    if (!_questTV) {
        _questTV = [[UITextView alloc] initWithFrame:CGRectMake(15, 5, self.view.frame.size.width - 30, 25)];
        _questTV.editable = YES;
        
        [_questTV.layer setCornerRadius:5];
        [_questTV.layer setBorderWidth:1];
        [_questTV.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];
        
        _questTV.delegate = self;
        _questTV.font = [UIFont systemFontOfSize:13];
        _questTV.textContainerInset = UIEdgeInsetsMake(5, 21, 5, 15);
        
        _questTV.layer.borderWidth = 1;
        _questTV.layer.borderColor = [[UIColor colorWithWhite:185.0/255.0 alpha:1] CGColor];
        _questTV.text = @"请输入";
        _questTV.textColor = [UIColor colorWithWhite:149.0/255.0 alpha:1];
        
        tvImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"write1.png"]];
        tvImageView.frame = CGRectMake(5, 5, 15, 15);
        [_questTV addSubview:tvImageView];
    }
    return _questTV;
}

-(UILabel *)tvLabel{
    if (!_tvLabel) {
        _tvLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 5, 200, 20)];
    }
    return _tvLabel;
}

- (UIToolbar *)toolBar{
    if (!_toolBar) {
        _toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.tableView.frame.origin.y + self.tableView.frame.size.height , self.view.frame.size.width , 35)];
    }
    return _toolBar;
}

- (UIButton *)completeBtn{
    if (!_completeBtn) {
        _completeBtn = [[UIButton alloc] initWithFrame:CGRectMake(260, 0, 50, 50)];
        _completeBtn.contentEdgeInsets = UIEdgeInsetsMake(9, 14, 19, 14);
        [_completeBtn setImage:[UIImage imageNamed:@"complete1.png"] forState:UIControlStateNormal];
        _completeBtn.enabled = NO;
//        [_completeBtn setBackgroundColor:[UIColor redColor]];
    }
    
    return _completeBtn;
}

- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 50, 50)];
        _cancelBtn.contentEdgeInsets = UIEdgeInsetsMake(11, 16, 21, 16);
        [_cancelBtn setImage:[UIImage imageNamed:@"cancel.png"] forState:UIControlStateNormal];
        [self.cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        [_cancelBtn setBackgroundColor:[UIColor redColor]];
    }
    return _cancelBtn;
}


#pragma mark  UITextViewDelegate协议
- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    NSLog(@"开始出现了!");
    
    [self.tableView setScrollEnabled:NO];
    [self.tableView setAllowsSelection:NO];
    self.questTV.frame = CGRectMake(20, 40, 280, 100);
    self.questTV.textContainerInset = UIEdgeInsetsZero;
    self.questTV.text = text;
    self.questTV.font = [UIFont systemFontOfSize:16];
    self.questTV.textColor = [UIColor blackColor];
    tvImageView.hidden = YES;
    
    self.tvLabel.center = CGPointMake(self.view.frame.size.width/2, 20);
    self.tvLabel.text = @"请输入";
    self.tvLabel.textAlignment = NSTextAlignmentCenter;
    self.tvLabel.hidden = NO;
    self.cancelBtn.hidden = NO;
    self.completeBtn.hidden = NO;
    
    [self.toolBar addSubview:self.tvLabel];
    [self.toolBar addSubview:self.completeBtn];
    [self.toolBar addSubview:self.cancelBtn];
}

- (void)textViewDidChange:(UITextView *)textView{
    NSLog(@"textViewDidChange");;
    if (self.questTV.text.length != 0) {
        self.completeBtn.enabled = YES;
        [self.completeBtn setImage:[UIImage imageNamed:@"complete2.png"] forState:UIControlStateNormal];
    }else
        self.completeBtn.enabled = NO;
    text = textView.text;
}

-(void)textViewDidEndEditing:(UITextView *)textView{
    self.questTV.font = [UIFont systemFontOfSize:13];
    [self.tableView setScrollEnabled:YES];
}

- (void)cancelBtnClick:(UIButton *)sender{
    [self.questTV resignFirstResponder];
    self.questTV.text = NULL;
    commentBackName=@"";
    [self toolBarChanged];
}

- (void)completeBtnClick:(UIButton *)sender {
    [self.questTV resignFirstResponder];
    self.questTV.text = NULL;
    [self toolBarChanged];
    self.completeBtn.enabled = NO;

    __weak commentViewController *weakSelf=self;
    NSMutableDictionary *dic= [[NSMutableDictionary alloc]initWithDictionary:weakSelf.commentRequestData];

   dic[_commentContentKey] = [commentBackName stringByAppendingString:text];
    
    self.commentRequestData=[[NSDictionary alloc]initWithDictionary:dic];
    [NetworkCenter AFRequestWithData:self.commentRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];

        if ([dic[@"result"] isEqualToString:@"success"]){
            [Alert showAlert:@"提交成功!"];
            text=NULL;
            self.numberOfComment++;
            [self.tableView beginRefreshing];
        }
        else {
            [Alert showAlert:@"提交失败!"];
            text = NULL;
        }
        
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"网络请求失败!"];
    }];
    commentBackName=@"";
}

- (void)toolBarChanged{
    self.completeBtn.hidden = YES;
    self.cancelBtn.hidden = YES;
    self.tvLabel.hidden = YES;
    self.toolBar.frame = CGRectMake(0, self.tableView.frame.origin.y + self.tableView.frame.size.height , self.view.frame.size.width , 35);
    self.questTV.frame = CGRectMake(self.questTV.frame.origin.x, 5, self.view.frame.size.width - 30, 25);
    
    if (self.questTV.text.length == 0) {
        self.questTV.text = @"请输入";
        self.questTV.textColor = [UIColor colorWithWhite:149.0/255.0 alpha:1];
        tvImageView.hidden = NO;
        self.questTV.textContainerInset = UIEdgeInsetsMake(5, 21, 5, 15);
    }else{
        self.questTV.contentInset = UIEdgeInsetsMake(5, 0, 5, 0);
        self.questTV.textColor = [UIColor blackColor];
    }
    
}

- (void)registerForKayboardNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwillHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardChange:(NSNotification *)aNotification{
    NSDictionary * info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    /*
     [UIView beginAnimations:nil context:NULL];
     [UIView setAnimationDelegate:self];
     [UIView setAnimationDuration:0.0];
     [UIView setAnimationBeginsFromCurrentState:YES];
     */
  
    [UIView animateWithDuration:0.1f
                     animations:^{
                         self.toolBar.frame = CGRectMake(self.toolBar.frame.origin.x, self.tableView.frame.origin.y + self.tableView.frame.size.height - kbSize.height - 120, self.view.frame.size.width, self.toolBar.frame.size.height + 150);
                     }];
    /*
     [UIView animateWithDuration:[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]
     animations:^{
     self.toolBar.frame = CGRectMake(self.toolBar.frame.origin.x, self.tableView.frame.origin.y + self.tableView.frame.size.height - kbSize.height - 120, self.view.frame.size.width, self.toolBar.frame.size.height + 150);
     }];
     
     */
    //  [UIView commitAnimations];
}

- (void)keyboardwillHidden:(NSNotification *)aNotification{
}

-(void)commentBackBtnClick:(NSString *)userName{
    NSString * myName = [constant getUserName];
    if ([userName isEqualToString:myName]) {
        [Alert showAlert:@"不能回复自己的评论!"];
        return;
    }
    [_questTV becomeFirstResponder];
    commentBackName = [NSString stringWithFormat:@"@%@  ",userName];
    NSLog(@"commentBackName = %@",commentBackName);
}
-(void)viewWillDisappear:(BOOL)animated{
    commentBackName = @"";
    [super viewWillDisappear:animated];
}
@end


